/**
 * 
 */
package com.littleken.browser.authentication;

import com.littleken.core.config.loginType;
import com.littleken.core.config.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功跳转逻辑
 */
@Component("littlekenAuthenticationSuccessHandler")
@Slf4j
public class littlekenAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{

    @Autowired
    private ObjectMapper objectMapper;//把object转为json

    @Autowired
    private SecurityProperties securityproperties;

    /**
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication 登录信息
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //log.error("登录成功");
        //json登录
        if(loginType.JSON.equals(securityproperties.getBrowser().getLogintype())){
            httpServletResponse.setContentType("application/json;charset=UTF-8");//告诉浏览器返回的是json数据
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(authentication));//返回登录信息
        }else {
            //html跳转
            super.onAuthenticationSuccess(httpServletRequest, httpServletResponse, authentication);
        }
    }
}
